 var commentList = new Array();
 var commentListIndex = 0;
 var canvas, context, canvaso, contexto;
 var cx,cy,cw,ch;
 
// Keep everything in anonymous function, called on window load.
if(window.addEventListener) {
    window.addEventListener('load', function () {
        
        var undobtn = document.getElementById('btn1');
        var submitbtn = document.getElementById('submitbtn');
        var img = new Image();
        var tbox1 = document.getElementById('txt1');
        var tbox2 = document.getElementById('txt2');
        var tbox3 = document.getElementById('txt3');
        var tbox4 = document.getElementById('txt4');
        
        var tc_id,tp_id,tct_id;
        var comment;
        var tcomment_id;
        tc_id=c_id;
        tp_id=p_id;
        tct_id=ct_id;
        tcomment_id=comment_id;
        
        //To hold the data for each action on the screen
        var undoHistory = new Array();
        var undoIndex = 0;
              
        var status = '1';
        var submit_state;
        // The active tool instance.
        var tool;
        
        //  var tool_default = 'line';
        var tool_default = 'rect';
        
        function init () {
            // Find the canvas element.
            canvaso = document.getElementById('imageView');
            //    img.src = 'mygraph.png';
            img.src = i_path;
            submit_state = false;
            if (!canvaso) {
                alert('Error: I cannot find the canvas element!');
                return;
            }

            if (!canvaso.getContext) {
                alert('Error: no canvas.getContext!');
                return;
            }

            // Get the 2D canvas context.
            contexto = canvaso.getContext('2d');
            contexto.drawImage(img, 0,0);
            if (!contexto) {
                alert('Error: failed to getContext!');
                return;
            }

            // Add the temporary canvas.
            var container = canvaso.parentNode;
            //canvas = document.getElementById('imageTemp');
            canvas = document.createElement('canvas');
            if (!canvas) {
                alert('Error: I cannot create a new canvas element!');
                return;
            }

            canvas.id     = 'imageTemp';
            canvas.width  = canvaso.width;
            canvas.height = canvaso.height;
            container.appendChild(canvas);

            context = canvas.getContext('2d');

            // Get the tool select input.
            var tool_select = document.getElementById('dtool');
            if (!tool_select) {
                alert('Error: failed to get the dtool element!');
                return;
            }
            //tool_select = document.getElementById('tool_default');
            tool_select.addEventListener('change', ev_tool_change, false);

            // Activate the default tool.
            if (tools[tool_default]) {
                tool = new tools[tool_default]();
                tool_select.value = tool_default;
            }

            // Attach the mousedown, mousemove and mouseup event listeners.
            canvas.addEventListener('mousedown', ev_canvas, false);
            canvas.addEventListener('mousemove', ev_canvas, false);
            canvas.addEventListener('mouseup',   ev_canvas, false);
        }
      
        function sendCoordinate(){
            //      alert("send coordinate function");
            //alert(cx+","+cy+","+cw+","+ch);
            comment=document.getElementById('comments').value;
            //        alert(comment);
                    
            $.ajax({
                type: "POST",
                url: "../ajax/sendCoordinate",
                data:
                {
                    comment_id:tcomment_id,
                    c_id:tc_id,
                    p_id:tp_id,
                    ct_id:tct_id,
                    co_x:cx, 
                    co_y:cy, 
                    co_w:cw,
                    co_h:ch, 
                    comment:comment,
                    status:status            
                },
            
                dataType: "json",
                success: function(data) {
                    alert("send success ");
                    document.getElementById('submitbtn').disabled = true;
                    submit_state=false;
                    getCoordinate();
                },
                error: function(data) { 
                    alert("send error" ); 
                }
            });       
        }
        
        function getCoordinate(){        
            $.ajax({
                type: "POST",
                url: "../ajax/getCoordinate",
                data:
                {
                    c_id:tc_id,
                    p_id:tp_id,
                    ct_id:tct_id
                },
                dataType: "json",
                success: function(data) {
                    alert("get success ");
                },
                error: function(data) { 
                    alert("get error" ); 
                }
            });       
        }
                            
        submitbtn.onclick = function(){
            status='1';
            tcomment_id=parseInt(tcomment_id)+parseInt(1);
            addNewCommment();           
            submit_state = true;
            //sendCoordinate();
            //getCoordinate();            
        }
        
        undobtn.onclick=function(){
            //    alert('Undo');
            //    context.clearRect(cx, cy, cw-100, ch-100);
            tcomment_id=comment_id;
            alert(tcomment_id);
            contexto.clearRect(0, 0, canvas.width, canvas.height);
            contexto.drawImage(img, 0,0);
            document.getElementById('submitbtn').disabled = true;
            
        //            if(undoIndex > 0)
        //            {
        //                var i;
        //                for (i=0;i<undoIndex-1;i++)
        //                {
        //                    var r = new Object();
        //                    r.x=undoHistory[i].x;
        //                    r.y=undoHistory[i].y;
        //                    r.w=undoHistory[i].w;
        //                    r.h=undoHistory[i].h;
        //                    context.strokeRect(r.x,r.y,r.w,r.h);
        //                }
        //            }
        //            undoIndex = undoIndex - 1;

        }

 
        // The general-purpose event handler. This function just determines the mouse 
        // position relative to the canvas element.
        function ev_canvas (ev) {
            if (ev.layerX || ev.layerX == 0) { // Firefox
                ev._x = ev.layerX;
                ev._y = ev.layerY;
            } else if (ev.offsetX || ev.offsetX == 0) { // Opera
                ev._x = ev.offsetX;
                ev._y = ev.offsetY;
            }

            // Call the event handler of the tool.
            var func = tool[ev.type];
            if (func) {
                func(ev);
            }
        }

        // The event handler for any changes made to the tool selector.
        function ev_tool_change (ev) {
            if (tools[this.value]) {
                tool = new tools[this.value]();
            }
        }

 
        // This function draws the #imageTemp canvas on top of #imageView, after which 
        // #imageTemp is cleared. This function is called each time when the user 
        // completes a drawing operation.
        function img_update () {
            //contexto.drawImage(canvas, 0, 0);
            //contexto.fillStyle    = '#00f';
            //contexto.font         = 'italic 30px sans-serif';
            //contexto.fillText  (tcomment_id, cx+20, cy+20);
            //context.clearRect(0, 0, canvas.width, canvas.height);
        }

        // This object holds the implementation of each drawing tool.
        var tools = {};


        // The rectangle tool.
        tools.rect = function () {
            var tool = this;
            this.started = false;

            this.mousedown = function (ev) {                                
                document.getElementById('submitbtn').disabled = true;
                //                tcomment_id=parseInt(tcomment_id)-parseInt(1);
                tool.started = true;
                tool.x0 = ev._x;
                tool.y0 = ev._y;
            //                tbox1.value = tool.x0;
            //                tbox2.value = tool.y0;
            };

            this.mousemove = function (ev) {
                if (!tool.started) {
                    return;
                }

                var x = Math.min(ev._x,  tool.x0),
                y = Math.min(ev._y,  tool.y0),
                w = Math.abs(ev._x - tool.x0),
                h = Math.abs(ev._y - tool.y0);

                //                tbox3.value = ev._x;
                //                tbox4.value = ev._y;
                
                updateDrawing();
                if (!w || !h) {
                    return;
                }
   
                cx=x;
                cy=y;
                cw=w;
                ch=h;
                
                context.strokeStyle = '#f00';
                context.strokeRect(x,y,w,h);         
            };

            this.mouseup = function (ev) {
                if (tool.started) {
                    document.getElementById('submitbtn').disabled = false;
                    tool.mousemove(ev);
                    tool.started = false;
                    var x = Math.min(ev._x,  tool.x0),
                    y = Math.min(ev._y,  tool.y0),
                    w = Math.abs(ev._x - tool.x0),
                    h = Math.abs(ev._y - tool.y0);
                    var ref = new Object;
                    ref.x = x;
                    ref.y = y;
                    ref.w = w;
                    ref.h = h;
                    undoHistory[undoIndex] = ref;
                    undoIndex = undoIndex + 1;                   
                    if (tcomment_id==0)
                    {
                        tcomment_id = 1;
                    }
                    else
                    {            
                        tcomment_id=parseInt(tcomment_id)+parseInt(1);
                    }
                    
                    img_update();
                    if (submit_state==false)
                    {                    
                        tcomment_id=parseInt(tcomment_id)-parseInt(1);
                    }                
                }
            };
        };

        //  // The drawing pencil.
        //  tools.pencil = function () {
        //    var tool = this;
        //    this.started = false;
        //
        //    // This is called when you start holding down the mouse button.
        //    // This starts the pencil drawing.
        //    this.mousedown = function (ev) {
        //        context.beginPath();
        //        context.moveTo(ev._x, ev._y);
        //        tool.started = true;
        //    };
        //
        //    // This function is called every time you move the mouse. Obviously, it only 
        //    // draws if the tool.started state is set to true (when you are holding down 
        //    // the mouse button).
        //    this.mousemove = function (ev) {
        //      if (tool.started) {
        //        context.lineTo(ev._x, ev._y);
        //        context.stroke();
        //      }
        //    };
        //
        //    // This is called when you release the mouse button.
        //    this.mouseup = function (ev) {
        //      if (tool.started) {
        //        tool.mousemove(ev);
        //        tool.started = false;
        //        img_update();
        //      }
        //    };
        //  };
        //  
        //  // The line tool.
        //  tools.line = function () {
        //    var tool = this;
        //    this.started = false;
        //
        //    this.mousedown = function (ev) {
        //      tool.started = true;
        //      tool.x0 = ev._x;
        //      tool.y0 = ev._y;
        //    };
        //
        //    this.mousemove = function (ev) {
        //      if (!tool.started) {
        //        return;
        //      }
        //
        //      context.clearRect(0, 0, canvas.width, canvas.height);
        //
        //      context.beginPath();
        //      context.moveTo(tool.x0, tool.y0);
        //      context.lineTo(ev._x,   ev._y);
        //      context.stroke();
        //      context.closePath();
        //    };
        //
        //    this.mouseup = function (ev) {
        //      if (tool.started) {
        //        tool.mousemove(ev);
        //        tool.started = false;
        //        img_update();
        //      }
        //    };
        //  };

        init();
        loadCommentFromDB();

    }, false);
}

function onMouseOver(element,i){
    context.strokeStyle = '#f00';    
    context.strokeRect(commentList[i].x,commentList[i].y,commentList[i].w,commentList[i].h);    
    element.bgColor='#EEEEEE';
}

function onMouseOut(element){
    updateDrawing();
    element.bgColor='#FFFFFF';
}
                          
function del(index){   
    commentListIndex = commentListIndex-1;
    for(i=index;i<commentListIndex;i++){
        commentList[i] = commentList[i+1];
    }
    commentList[commentListIndex] = null;
    updateDrawing();
    updateCommentDetail();
}

function updateDrawing(){
    context.clearRect(0, 0, canvas.width, canvas.height);    
    for(i = 0; i < commentListIndex; i++){        
        context.strokeStyle = '#0000cd';    
        context.strokeRect(commentList[i].x,commentList[i].y,commentList[i].w,commentList[i].h); 
    }  
}

function updateCommentDetail(){            
    var commentDetail = '';    
    for(i = 0; i < commentListIndex; i++){        
        commentDetail += '<tr style=\"cursor:pointer;\" onMouseover=\"onMouseOver(this,'+i+')\" onMouseout=\"onMouseOut(this,'+i+')\">\n\
                          <td>'+i+'</td><td id="comment'+i+'" onclick="editComment('+i+')">'+commentList[i].c+'</td>\n\
                          <td align=center><a href=\"javascript:del('+i+')\"><img src=\'../assets/icon/cancel_48.png\' width=32 height=32/></a></td></tr>';
    }            
    document.getElementById('commentDetail').innerHTML = commentDetail;
}

var editIndex;
function editComment(i){
    var $dialog = $('<div></div>')
		.html('<textarea id="editcomments" name="editcomments" rows="6" cols="40">'+commentList[i].c+'</textarea>')
		.dialog({
			autoOpen: false,
                        width: 500,
			title: 'Edit Comment',
                        modal: true,
			buttons: {
                            Update: function() {                             
                               updateComment(i,$('textarea#editcomments').val());
                               updateCommentDetail();
                               $(this).dialog( "close" );
                            }
                        }
		});
    $dialog.dialog('open');	
}

function updateComment(i,comment){
   
    if(comment !=''){
        commentList[i].c = comment;
    }
}

function addNewCommment(){            
    var comment = document.getElementById('comments').value;
    if (comment == '') {
        alert('Please input comment!!');
        return;
    }
            
    if(cx==null){
        alert('Please draw rectangle first');
        return;
    }
            
    commentList[commentListIndex] = new Object;            
    commentList[commentListIndex].x = cx;
    commentList[commentListIndex].y = cy;
    commentList[commentListIndex].w = cw;
    commentList[commentListIndex].h = ch;
    commentList[commentListIndex].c = comment;
    commentList[commentListIndex].show = true;
    commentListIndex = commentListIndex+1;
    
    document.getElementById('comments').value = "";
    updateDrawing();
    updateCommentDetail();
}

function loadCommentFromDB(){
    $.ajax({
                type: "POST",
                url: "../ajax/getCoordinate",
                data:
                {
                    c_id:c_id,
                    p_id:p_id,
                    ct_id:ct_id
                },
                dataType: "json",
                success: function(data) {                    
                    $.each(data, function(key, val) {                       
                      commentList[commentListIndex] = new Object;     
                      commentList[commentListIndex].x = val.x
                      commentList[commentListIndex].y = val.y
                      commentList[commentListIndex].w = val.w
                      commentList[commentListIndex].h = val.h
                      commentList[commentListIndex].c = val.comment                                                                  
                      commentListIndex = commentListIndex+1;
                    });
                    
                    updateDrawing();
                    updateCommentDetail();
                },
                error: function(data) { 
                    alert("get error" ); 
                }
            });       
}

function save(){
    var sendData='[';
    
    /*
     [{"c_id":"8","p_id":"21","ct_id":"48","co_id":"0","co_x":"10","co_y":"10","co_w":"100","co_h":"100","comment":"aaa","status":"1"},
      {"c_id":"8","p_id":"21","ct_id":"48","co_id":"1","co_x":"20","co_y":"20","co_w":"20","co_h":"20","comment":"Test","status":"1"}
     ]
    */
   
    for(i = 0; i < commentListIndex; i++){   
        if(i!=commentListIndex-1){
            sendData += '{"id":"'+i+'","x":"'+commentList[i].x+'","y":"'+commentList[i].y+'","w":"'+commentList[i].w+'","h":"'+commentList[i].h+'","comment":"'+commentList[i].c+'"},';  
        }else{
            sendData += '{"id":"'+i+'","x":"'+commentList[i].x+'","y":"'+commentList[i].y+'","w":"'+commentList[i].w+'","h":"'+commentList[i].h+'","comment":"'+commentList[i].c+'"}]';  
        }      
    }
    
    if(commentListIndex==0){
       sendData = '';
    }
    
    $.ajax({
        type: "POST",
        url: "../ajax/sendCoordinate",
        data:
        {           
            c_id:c_id,
            p_id:p_id,
            ct_id:ct_id,
            data:sendData         
        },
                   
        success: function(data) {
            alert("All comments are Saved !!");           
        },
        error: function(data) { 
            alert("Save error" ); 
        }
    });         
}

// vim:set spell spl=en fo=wan1croql tw=80 ts=2 sw=2 sts=2 sta et ai cin fenc=utf-8 ff=unix:

